<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="4"
        ><div class="grid-content bg-purple">
          <el-button type="primary" plain @click="addShow = true"
            >添加角色
          </el-button>
        </div></el-col
      >
      <el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
    </el-row>
    <el-table
      stripe
      border
      class="mt-15"
      :data="roleList"
      style="width: 100%"
      v-loading="isLoading"
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            v-for="firstChildren in scope.row.children"
            :key="firstChildren.id"
          >
            <el-col :span="4">
              <el-tag
                closable
                @close="delRoleRight(scope.row, firstChildren.id)"
                >{{ firstChildren.authName }}</el-tag
              >
              <i
                class="el-icon-arrow-right"
                v-if="firstChildren.children.length !== 0"
              ></i>
            </el-col>
            <el-col :span="20">
              <el-row
                v-for="secondChildren in firstChildren.children"
                :key="secondChildren.id"
              >
                <el-col :span="4">
                  <el-tag
                    closable
                    type="success"
                    @close="delRoleRight(scope.row, secondChildren.id)"
                    >{{ secondChildren.authName }}</el-tag
                  >
                  <i
                    class="el-icon-arrow-right"
                    v-if="secondChildren.children.length !== 0"
                  ></i>
                </el-col>
                <el-col :span="20">
                  <el-tag
                    closable
                    type="warning"
                    v-for="thirdChildren in secondChildren.children"
                    :key="thirdChildren.id"
                    @close="delRoleRight(scope.row, thirdChildren.id)"
                  >
                    {{ thirdChildren.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row v-if="scope.row.children.length === 0">
            <el-col :span="24">该角色没有分配权限，请前往分配！</el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="角色id" prop="id"> </el-table-column>
      <el-table-column label="角色名称" prop="roleName"> </el-table-column>
      <el-table-column label="描述" prop="roleDesc"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            content="编辑角色"
            placement="top"
          >
            <el-button
              size="mini"
              type="primary"
              plain
              icon="el-icon-edit"
              @click="getSingleRole(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="删除角色"
            placement="top"
          >
            <el-button
              size="mini"
              type="danger"
              plain
              icon="el-icon-delete"
              @click="delRole(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="角色授权"
            placement="top"
          >
            <el-button
              size="mini"
              type="warning"
              plain
              icon="el-icon-s-custom"
              @click="queryRights(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑角色弹框 -->
    <el-dialog :visible.sync="editShow" title="角色编辑" width="500px">
      <el-form :model="editForm" label-width="80px" ref="editRoleForm">
        <el-form-item label="角色id" prop="roleId">
          <el-input v-model="editForm.roleId" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary" @click="editRole('editRoleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加角色弹框 -->
    <el-dialog title="添加角色" :visible.sync="addShow" width="500px">
      <el-form :model="addForm" label-width="80px" ref="addRoleForm">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleShow = false">取 消</el-button>
        <el-button
          type="primary"
          native-type="submit"
          @click="addRole('addRoleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 角色授权弹框 -->
    <el-dialog title="角色授权" :visible.sync="authShow" width="500px">
      <div class="tree-container">
        <el-tree
          :data="rightList"
          show-checkbox
          ref="tree"
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="selectedRights"
          :props="defaultProps"
        >
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="authShow = false">取 消</el-button>
        <el-button type="primary" @click="authRole">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getRoleList,
  delRoleRight,
  getRightList,
  editRole,
  getSingleRole,
  addRole,
  delRole,
  authRole
} from "@/api/index";
export default {
  name: "",
  data() {
    return {
      isLoading: false,
      roleList: [],
      rightList: [],
      //   编辑角色
      editShow: false,
      editForm: {
        roleId: 0,
        roleName: "",
        roleDesc: ""
      },
      //   添加角色
      addShow: false,
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      //   角色授权
      authShow: false,
      curRole: "",
      selectedRights: [],
      defaultProps: {
        children: "children", // // 树形组件展示的数据源
        label: "authName" // 树形组件显示的标题字段
      }
    };
  },
  watch: {},
  props: {},
  components: {},
  computed: {},
  mounted() {},
  methods: {
    //   获取角色列表
    async getRoleList() {
      this.isLoading = true;
      await getRoleList().then(({ data, meta }) => {
        if (meta.status == 200) {
          this.roleList = data;
          this.isLoading = false;
        }
      });
    },
    // 删除角色权限
    async delRoleRight(row, rightId) {
      await delRoleRight({ roleId: row.id, rightId: rightId }).then(
        ({ data, meta }) => {
          if (meta.status == 200) {
            row.children = data;
            this.$message.success(meta.msg);
          } else {
            this.$message.warning(meta.msg);
          }
        }
      );
    },
    // 编辑角色信息
    // 1.查询角色信息
    async getSingleRole(row) {
      await getSingleRole(row.id).then(res => {
        if (res.meta.status === 200) {
          this.editForm.roleName = res.data.roleName;
          this.editForm.roleDesc = res.data.roleDesc;
          this.editForm.roleId = res.data.roleId;
        } else {
          this.$message.warning(res.meta.msg);
        }
      });
      this.editShow = true;
    },
    // 2.提交角色信息
    async editRole(formName) {
      await this.$refs[formName].validate(valide => {
        if (valide) {
          editRole(this.editForm).then(res => {
            if (res.meta.status === 200) {
              this.$message.success("修改成功");
              this.editShow = false;
              this.getRoleList();
            } else {
              this.$message.warning(res.meta.msg);
            }
          });
        }
      });
    },
    // 添加角色
    async addRole(formName) {
      await this.$refs[formName].validate(valide => {
        if (valide) {
          addRole(this.addForm).then(res => {
            if (res.meta.status === 201) {
              this.$message.success(res.meta.msg);
            } else {
              this.$message.warning(res.meta.msg);
            }
            this.addShow = false;
            this.addForm.roleName = "";
            this.addForm.roleDesc = "";
            this.getRoleList();
          });
        }
      });
    },
    // 删除角色
    async delRole(row) {
      await this.$confirm("真的要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let data = await delRole(row.id);
          data.meta.status == 200
            ? this.$message.success(data.meta.msg)
            : this.$message.warning(data.meta.msg);
          this.getRoleList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 角色授权
    // 1.查询权限列表
    async queryRights(row) {
      this.curRole = row;
      await getRightList({ type: "tree" }).then(({ data, meta }) => {
        if (meta.status == 200) {
          this.rightList = data;
          this.selectedRights = [];
          //   2.选中角色已有权限
          this.checkedRight(row, this.selectedRights);
          this.authShow = true;
        } else {
          this.$message.error(meta, msg);
        }
      });
    },
    // 3.提交角色新增权限
    authRole() {
      let rids = this.$refs.tree.getCheckedKeys().join(",");
      authRole(this.curRole.id, { rids }).then(({ meta }) => {
        if (meta.status == 200) {
          this.$message.success(meta.msg);
          this.authShow = false;
          this.getRoleList();
        } else {
          this.$message.error(meta, msg);
        }
      });
    },
    checkedRight(arr1, arr2) {
      if (!arr1.children) {
        return arr2.push(arr1.id);
      } else {
        arr1.children.forEach(item => {
          return this.checkedRight(item, arr2);
        });
      }
    }
  },
  created() {
    this.getRoleList();
  },
  filters: {}
};
</script>

<style scoped lang="scss">
.tree-container {
  height: 300px;
  overflow: auto;
}
.dialog-footer {
  line-height: 0;
}
.el-col {
  line-height: 0;
}
</style>
